package config.db

import dev.miku.r2dbc.mysql.MySqlConnectionConfiguration
import dev.miku.r2dbc.mysql.MySqlConnectionFactory
import io.r2dbc.spi.ConnectionFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.PropertySource
import org.springframework.core.io.ClassPathResource
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories
import org.springframework.r2dbc.connection.init.CompositeDatabasePopulator
import org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer
import org.springframework.r2dbc.connection.init.ResourceDatabasePopulator
import org.springframework.stereotype.Component
import javax.annotation.Resource

/**
 * @author  fly
 * @date  2021/7/29 10:55
 * @version 1.0
 */

@ConfigurationProperties(prefix = "r2dbc")
@Component
class R2dbcProperties(

    @Value("r2dbc.host")
    var host: String? = "121.4.149.47",

    @Value("r2dbc.port")
    var port: Int? = 3306,

    @Value("r2dbc.username")
    var username: String? = "root",

    @Value("r2dbc.password")
    var password: String? = "TianWo123..",

    @Value("r2dbc.databaseName")
    var databaseName: String? = "youyou",
)

@Configuration
@EnableConfigurationProperties(R2dbcProperties::class)
@EnableR2dbcRepositories
class R2dbcConfig {

    @Resource
    lateinit var r2dbcProperties: R2dbcProperties


    @Bean("r2bcConnectionFactory")
    fun connectionFactory(): ConnectionFactory = MySqlConnectionFactory
        .from(MySqlConnectionConfiguration.builder()
            .host(r2dbcProperties.host!!)
            .port(r2dbcProperties.port!!)
            .username(r2dbcProperties.username!!)
            .password(r2dbcProperties.password!!)
            .database(r2dbcProperties.databaseName!!)
            .build())

    @Bean
    fun initializer(
        @Qualifier("r2bcConnectionFactory") connectionFactory: ConnectionFactory,
    ): ConnectionFactoryInitializer = ConnectionFactoryInitializer().apply {
        setConnectionFactory(connectionFactory)
        setDatabasePopulator(CompositeDatabasePopulator().apply {
           /* addPopulators(ResourceDatabasePopulator(ClassPathResource("schema.sql")))
            addPopulators(ResourceDatabasePopulator(ClassPathResource("data.sql")))*/
        })
    }

}